package com.huhao.wshare;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static com.huhao.wshare.Config.*;

public class RegisterActivity extends BaseActivity {
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final long COUNTDOWN_TIME = 5 * 60 * 1000; // 五分钟倒计时
    private static final long COUNT_DOWN_INTERVAL = 1000; // 每秒更新一次

    private EditText etEmail, etVerificationCode, etPhone, etAccount, etUsername, etPassword;
    private RadioGroup rgGender;
    private Button btnGetVerificationCode, btnRegister;
    private TextView tvGoLogin;
    private OkHttpClient client = new OkHttpClient();
    private CountDownTimer countDownTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        setupListeners();
    }

    private void initViews() {
        etEmail = findViewById(R.id.et_email);
        etVerificationCode = findViewById(R.id.et_verification_code);
        etPhone = findViewById(R.id.et_phone);
        etAccount = findViewById(R.id.et_account);
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        rgGender = findViewById(R.id.rg_gender);
        btnGetVerificationCode = findViewById(R.id.btn_get_verification_code);
        btnRegister = findViewById(R.id.btn_register);
        tvGoLogin = findViewById(R.id.tv_go_login);
    }

    private void setupListeners() {
        btnGetVerificationCode.setOnClickListener(v -> sendVerificationCode());
        btnRegister.setOnClickListener(v -> attemptRegister());
        tvGoLogin.setOnClickListener(v -> finish());
    }

    private void sendVerificationCode() {
        String email = etEmail.getText().toString().trim();
        if (TextUtils.isEmpty(email)) {
            etEmail.setError("请输入邮箱");
            etEmail.requestFocus();
            return;
        }

        // 开始倒计时
        startCountDown();

        JSONObject json = new JSONObject();
        try {
            json.put("email", email);
        } catch (JSONException e) {
            Log.e("Register", "构建 JSON 失败", e);
            Toast.makeText(this, "构建请求失败", Toast.LENGTH_SHORT).show();
            stopCountDown();
            return;
        }

        RequestBody body = RequestBody.create(json.toString(), JSON);
        Request request = new Request.Builder()
                .url(SEND_CODE_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(RegisterActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                    stopCountDown();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body() != null ? response.body().string() : "";
                runOnUiThread(() -> handleVerificationCodeResponse(response.code(), responseData));
            }
        });
    }

    private void startCountDown() {
        btnGetVerificationCode.setEnabled(false);
        btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.darker_gray));

        countDownTimer = new CountDownTimer(COUNTDOWN_TIME, COUNT_DOWN_INTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                btnGetVerificationCode.setText(seconds + "秒后重试");
            }

            @Override
            public void onFinish() {
                btnGetVerificationCode.setEnabled(true);
                btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
                btnGetVerificationCode.setText("获取验证码");
            }
        }.start();
    }

    private void stopCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
            btnGetVerificationCode.setEnabled(true);
            btnGetVerificationCode.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
            btnGetVerificationCode.setText("获取验证码");
        }
    }

    private void handleVerificationCodeResponse(int code, String responseData) {
        try {
            JSONObject json = new JSONObject(responseData);
            if (code == 200) {
                Toast.makeText(this, "验证码已发送到您的邮箱，请查收", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, json.optString("message", "验证码发送失败"), Toast.LENGTH_SHORT).show();
                stopCountDown();
            }
        } catch (JSONException e) {
            Toast.makeText(this, "解析响应失败", Toast.LENGTH_SHORT).show();
            Log.e("Register", "解析 JSON 失败", e);
            stopCountDown();
        }
    }

    private void attemptRegister() {
        String email = etEmail.getText().toString().trim();
        String verificationCode = etVerificationCode.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String account = etAccount.getText().toString().trim();
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String gender = getSelectedGender();

        if (TextUtils.isEmpty(email)) {
            etEmail.setError("请输入邮箱");
            etEmail.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(verificationCode)) {
            etVerificationCode.setError("请输入验证码");
            etVerificationCode.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            etPhone.setError("请输入手机号");
            etPhone.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(account)) {
            etAccount.setError("请输入账户名");
            etAccount.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(gender)) {
            Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
            return;
        }

        JSONObject json = new JSONObject();
        try {
            json.put("email", email);
            json.put("verificationCode", verificationCode);
            json.put("phone", phone);
            json.put("account", account);
            json.put("username", username);
            json.put("password", password);
            json.put("gender", gender);
        } catch (JSONException e) {
            Log.e("Register", "构建 JSON 失败", e);
            Toast.makeText(this, "构建请求失败", Toast.LENGTH_SHORT).show();
            return;
        }

        RequestBody body = RequestBody.create(json.toString(), JSON);
        Request request = new Request.Builder()
                .url(REGISTER_URL)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(RegisterActivity.this, "网络错误，请稍后重试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body() != null ? response.body().string() : "";
                runOnUiThread(() -> handleRegisterResponse(response.code(), responseData));
            }
        });
    }

    private String getSelectedGender() {
        int selectedId = rgGender.getCheckedRadioButtonId();
        if (selectedId == -1) {
            return "empty";
        }
        RadioButton radioButton = findViewById(selectedId);
        String genderText = radioButton.getText().toString();
        if ("男".equals(genderText)) {
            return "man";
        } else if ("女".equals(genderText)) {
            return "woman";
        } else {
            return "empty";
        }
    }


    private void handleRegisterResponse(int code, String responseData) {
        try {
            JSONObject json = new JSONObject(responseData);
            if (code == 200) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Log.e("Register", "注册失败: " + json.optString("message", "未知错误"));
                Toast.makeText(this, json.optString("message", "注册失败"), Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            Toast.makeText(this, "解析响应失败", Toast.LENGTH_SHORT).show();
            Log.e("Register", "解析 JSON 失败", e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}